import { defineStore } from 'pinia'
import{ loginApi, loginByCodeApi}from '@/api/user'
import { setToken,getToken ,removeToken} from '@/utils/token'
import {setUserInfo,getUserInfo,removeUserInfo } from '@/utils/userInfo'
import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus'
//定义并导出仓库
export const useUserStore = defineStore('user',{
    //定义共享数据
    state:()=>({
        //从本地存储中获取token
        token:getToken() || '',
        //从本地存储中获取userInfo
        userInfo:getUserInfo() ||{}

    }),
    //修改数据的函数
    actions:{

        //设置token
        setToken(token){
            this.token = token
            setToken(token)
        },
        //设置userInfo
        setUserInfo(userInfo){
            //pinia中存userInfo
            this.userInfo = userInfo
            //本地存储中存userInfo
            setUserInfo(userInfo)
        },
       
        //发起登录请求 存储token到pinia
        async loginAction(loginForm){
            const resp = await loginApi(loginForm)
            if(resp.data.code === 200){
                const userInfo = resp.data.data
                localStorage.setItem('password',loginForm.password)
                this.setUserInfo(userInfo)
                const userToken = document.cookie.split('=')[1]
                this.setToken(userToken)
            }
        },
        async loginActionByCode(loginForm){
            const resp = await loginByCodeApi(loginForm)
            console.log(resp)
            if(resp.data.code === 200){
                const userInfo = resp.data.data
                this.setUserInfo(userInfo)
                const userToken = document.cookie.split('=')[1]
                this.setToken(userToken)
            }
        },
        //退出登录
        logout(){
            //清理pinia中的token和用户信息
            this.token = ''
            this.userInfo = {}
            //清理本地存储中的token 和userInfo
            removeToken()
            removeUserInfo()

        }
    }
})
